// folder-management.js - 处理名片夹管理功能

// 当前操作的名片夹ID
let currentFolderId = null;

document.addEventListener('DOMContentLoaded', async () => {
  // 从localStorage获取当前用户和令牌
  const currentUser = JSON.parse(localStorage.getItem('currentUser'));
  const token = localStorage.getItem('token');
  
  if (!currentUser || !token) {
    // 如果没有用户信息或令牌，重定向到登录页面
    window.location.href = 'login.html';
    return;
  }
  
  // 初始化事件监听器
  initEventListeners();
  
  // 加载名片夹数据
  await loadFolders();
});

/**
 * 初始化事件监听器
 */
function initEventListeners() {
  // 新建名片夹按钮
  document.getElementById('addFolderBtn').addEventListener('click', () => openModal());
  
  // 模态框关闭按钮
  document.querySelectorAll('.close').forEach(closeBtn => {
    closeBtn.addEventListener('click', function() {
      // 获取父级模态框并关闭
      const modal = this.closest('.modal');
      closeModal(modal);
    });
  });
  
  // 取消按钮
  document.getElementById('cancelBtn').addEventListener('click', () => {
    closeModal(document.getElementById('folderModal'));
  });
  
  // 取消删除按钮
  document.getElementById('cancelDeleteBtn').addEventListener('click', () => {
    closeModal(document.getElementById('confirmModal'));
  });
  
  // 确认删除按钮
  document.getElementById('confirmDeleteBtn').addEventListener('click', async () => {
    await deleteFolder();
  });
  
  // 表单提交事件
  document.getElementById('folderForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    await saveFolder();
  });
  
  // 点击模态框背景关闭模态框
  window.addEventListener('click', (e) => {
    if (e.target.classList.contains('modal')) {
      closeModal(e.target);
    }
  });
}

/**
 * 加载名片夹数据
 */
async function loadFolders() {
  try {
    showLoading();
    
    // 检查令牌是否存在
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('认证失败：未找到令牌');
    }
    
    // 获取名片夹列表
    const response = await window.api.folders.getAll();
    
    if (!response.success) {
      throw new Error('获取名片夹数据失败：' + (response.message || ''));
    }
    
    const folders = response.folders;
    const folderListContainer = document.getElementById('folderList');
    
    if (!folders || folders.length === 0) {
      // 显示空状态
      folderListContainer.innerHTML = `
        <div class="empty-state">
          <p>您还没有创建任何名片夹</p>
          <button class="success" onclick="openModal()">创建第一个名片夹</button>
        </div>
      `;
      return;
    }
    
    // 创建表格
    const table = document.createElement('table');
    
    // 添加表头
    const tableHead = document.createElement('thead');
    tableHead.innerHTML = `
      <tr>
        <th style="width: 30%;">名称</th>
        <th style="width: 50%;">描述</th>
        <th style="width: 20%;">操作</th>
      </tr>
    `;
    table.appendChild(tableHead);
    
    // 添加表体
    const tableBody = document.createElement('tbody');
    
    folders.forEach(folder => {
      const row = document.createElement('tr');
      
      row.innerHTML = `
        <td>${folder.name}</td>
        <td>${folder.description || '无描述'}</td>
        <td>
          <div class="button-group">
            <button class="edit-btn" data-id="${folder.id}">编辑</button>
            <button class="danger delete-btn" data-id="${folder.id}">删除</button>
          </div>
        </td>
      `;
      
      tableBody.appendChild(row);
    });
    
    table.appendChild(tableBody);
    
    // 清空容器并添加表格
    folderListContainer.innerHTML = '';
    folderListContainer.appendChild(table);
    
    // 添加编辑和删除按钮的事件监听
    document.querySelectorAll('.edit-btn').forEach(btn => {
      btn.addEventListener('click', () => openModal(btn.dataset.id));
    });
    
    document.querySelectorAll('.delete-btn').forEach(btn => {
      btn.addEventListener('click', () => openDeleteConfirmation(btn.dataset.id));
    });
  } catch (error) {
    console.error('加载名片夹错误:', error);
    
    // 显示更详细的错误信息
    const errorMessage = error.message || '未知错误';
    
    document.getElementById('folderList').innerHTML = `
      <div class="alert alert-danger" style="color: #721c24; background-color: #f8d7da; padding: 10px; border-radius: 4px;">
        <p>加载名片夹失败: ${errorMessage}</p>
        <div style="margin-top: 10px;">
          <button onclick="location.reload()">重试</button>
          <button onclick="location.href='main.html'" style="margin-left: 10px;">返回主页</button>
        </div>
      </div>
    `;
    
    // 如果是认证错误，提供登录选项
    if (errorMessage.includes('认证失败') || errorMessage.includes('unauthorized')) {
      localStorage.removeItem('currentUser');
      localStorage.removeItem('token');
      
      setTimeout(() => {
        alert('登录已过期，请重新登录');
        window.location.href = 'login.html';
      }, 1000);
    }
  } finally {
    hideLoading();
  }
}

/**
 * 打开模态框
 * @param {string|null} folderId - 名片夹ID，如果是新建则为null
 */
async function openModal(folderId = null) {
  currentFolderId = folderId;
  const modal = document.getElementById('folderModal');
  const modalTitle = document.getElementById('modalTitle');
  const folderNameInput = document.getElementById('folderName');
  const folderDescriptionInput = document.getElementById('folderDescription');
  const folderIdInput = document.getElementById('folderId');
  
  // 重置表单
  document.getElementById('folderForm').reset();
  
  if (folderId) {
    // 编辑模式
    modalTitle.textContent = '编辑名片夹';
    showLoading();
    
    try {
      // 检查令牌是否存在
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('认证失败：未找到令牌');
      }
      
      // 获取名片夹详情
      const folders = await window.api.folders.getAll();
      const folder = folders.folders.find(f => f.id == folderId);
      
      if (!folder) {
        throw new Error('未找到名片夹');
      }
      
      // 填充表单
      folderNameInput.value = folder.name;
      folderDescriptionInput.value = folder.description || '';
      folderIdInput.value = folder.id;
    } catch (error) {
      console.error('获取名片夹详情错误:', error);
      alert('获取名片夹信息失败，请重试');
      closeModal(modal);
      return;
    } finally {
      hideLoading();
    }
  } else {
    // 新建模式
    modalTitle.textContent = '新建名片夹';
    folderIdInput.value = '';
  }
  
  // 显示模态框
  modal.style.display = 'block';
}

/**
 * 关闭模态框
 * @param {HTMLElement} modal - 要关闭的模态框元素
 */
function closeModal(modal) {
  if (modal) {
    modal.style.display = 'none';
  }
}

/**
 * 打开删除确认对话框
 * @param {string} folderId - 名片夹ID
 */
function openDeleteConfirmation(folderId) {
  currentFolderId = folderId;
  const modal = document.getElementById('confirmModal');
  modal.style.display = 'block';
}

/**
 * 保存名片夹（新建或编辑）
 */
async function saveFolder() {
  const folderName = document.getElementById('folderName').value.trim();
  const folderDescription = document.getElementById('folderDescription').value.trim();
  
  if (!folderName) {
    alert('请输入名片夹名称');
    return;
  }
  
  try {
    showLoading();
    
    // 检查令牌是否存在
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('认证失败：未找到令牌');
    }
    
    const folderData = {
      name: folderName,
      description: folderDescription
    };
    
    let response;
    
    if (currentFolderId) {
      // 编辑现有名片夹
      response = await window.api.folders.update(currentFolderId, folderData);
    } else {
      // 创建新名片夹
      response = await window.api.folders.create(folderData);
    }
    
    if (response.success) {
      // 关闭模态框
      closeModal(document.getElementById('folderModal'));
      
      // 重新加载名片夹列表
      await loadFolders();
    } else {
      throw new Error(response.message || '操作失败');
    }
  } catch (error) {
    console.error('保存名片夹错误:', error);
    alert(`保存名片夹失败: ${error.message || '未知错误'}`);
    
    // 如果是认证错误，跳转到登录页面
    if (error.message.includes('认证失败') || error.message.includes('unauthorized')) {
      localStorage.removeItem('currentUser');
      localStorage.removeItem('token');
      
      setTimeout(() => {
        alert('登录已过期，请重新登录');
        window.location.href = 'login.html';
      }, 1000);
    }
  } finally {
    hideLoading();
  }
}

/**
 * 删除名片夹
 */
async function deleteFolder() {
  if (!currentFolderId) {
    alert('未选择有效的名片夹');
    return;
  }
  
  try {
    showLoading();
    
    // 检查令牌是否存在
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('认证失败：未找到令牌');
    }
    
    // 调用删除API
    const response = await window.api.folders.delete(currentFolderId);
    
    if (response.success) {
      // 关闭确认对话框
      closeModal(document.getElementById('confirmModal'));
      
      // 重新加载名片夹列表
      await loadFolders();
    } else {
      throw new Error(response.message || '删除失败');
    }
  } catch (error) {
    console.error('删除名片夹错误:', error);
    alert(`删除名片夹失败: ${error.message || '未知错误'}`);
    
    // 如果是认证错误，跳转到登录页面
    if (error.message.includes('认证失败') || error.message.includes('unauthorized')) {
      localStorage.removeItem('currentUser');
      localStorage.removeItem('token');
      
      setTimeout(() => {
        alert('登录已过期，请重新登录');
        window.location.href = 'login.html';
      }, 1000);
    }
  } finally {
    hideLoading();
    currentFolderId = null;
  }
}

/**
 * 显示加载覆盖层
 */
function showLoading() {
  document.getElementById('loadingOverlay').style.display = 'flex';
}

/**
 * 隐藏加载覆盖层
 */
function hideLoading() {
  document.getElementById('loadingOverlay').style.display = 'none';
} 